IF OBJECT_ID (N'dbo.getOrderedProducts') IS NOT NULL
   DROP FUNCTION dbo.getOrderedProducts
GO

CREATE FUNCTION dbo.getOrderedProducts (@SalesOrderId int )
RETURNS @OrderedProducts TABLE 
(
	SalesOrderId int NOT NULL,    
	ProdutID int NOT NULL,
	ProductName varchar(255) NOT NULL,
	ProdOrderQty smallint NOT NULL,
	UnitPrice money NOT NULL,
	ProductTotal float NOT NULL
)
AS

BEGIN

	INSERT @OrderedProducts
		SELECT
			s.SalesOrderId, 
			s.ProductID, 
			p.Name,
			s.OrderQty,
			s.UnitPrice,
			OrderQty * UnitPrice as [ProductTotal]
		FROM Sales.SalesOrderDetail s INNER JOIN
			Production.Product p on s.ProductID = p.ProductID
		WHERE s.salesorderId=@SalesOrderId

	INSERT @OrderedProducts
		SELECT 
			@SalesOrderId,
			0,
			'TOTAL',
			0,
			0,
			SUM([ProductTotal]) AS [ProductTotal]
		FROM @OrderedProducts
		
   RETURN
END;
GO


SELECT * FROM getOrderedProducts(43659);